// FileUriHandlerPlugin.kt
package com.sanji.audio_test

import android.app.Activity
import android.content.Intent
import android.net.Uri
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.PluginRegistry
import android.widget.Toast
import com.sanji.audio_test.Preferences

/**
 * 文件URI处理插件
 * 提供Flutter调用文件URI处理功能的能力
 */
// FileUriHandlerPlugin.kt
class FileUriHandlerPlugin : FlutterPlugin, MethodCallHandler, ActivityAware, PluginRegistry.ActivityResultListener {
    private var channel: MethodChannel? = null
    private var activity: Activity? = null
    private var pendingResult: MethodChannel.Result? = null
    private var currentUriType: String? = null  // 添加这个变量来标识URI类型


    companion object {
        const val OPENING_STATEMENT = "opening_statement"
        // TODO: 添加其他URI类型可以根据需要添加更多类型
    }
    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "file_uri_handler")
        channel?.setMethodCallHandler(this)
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        // 检查activity是否可用
        if (activity == null) {
            result.error("NO_ACTIVITY", "Activity is not available", null)
            return
        }

        when (call.method) {
            "handleOpeningStatement" -> {
                pendingResult = result
                currentUriType = OPENING_STATEMENT
                FileUriHandler.handleOpeningStatement(activity!!)
                Toast.makeText(activity, "正在选择开场白文件...", Toast.LENGTH_SHORT).show()
            }
            else -> {
                result.notImplemented()
            }
        }
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel?.setMethodCallHandler(null)
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        activity = binding.activity
        binding.addActivityResultListener(this)
    }

    override fun onDetachedFromActivityForConfigChanges() {
        activity = null
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        activity = binding.activity
        binding.addActivityResultListener(this)
    }

    override fun onDetachedFromActivity() {
        activity = null
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
        if (requestCode == FileUriHandler.REQUEST_CODE_SELECT_FILE) {
            if (resultCode == Activity.RESULT_OK) {
                val uri = data?.data
                if (uri != null) {
                    // 根据类型保存URI到Preferences
                    if (activity != null && currentUriType != null) {
                        val preferences = Preferences(activity!!)
                        when (currentUriType) {
                            OPENING_STATEMENT -> preferences.openingStatement = uri
                            // TODO 根据需要可以添加更多类型
                        }
                    }
                    
                    pendingResult?.success(uri.toString())
                    Toast.makeText(activity, "成功获取文件URI", Toast.LENGTH_SHORT).show()
                } else {
                    pendingResult?.error("PICK_FILE_ERROR", "Failed to get file URI", null)
                    Toast.makeText(activity, "获取文件URI失败", Toast.LENGTH_SHORT).show()
                }
            } else {
                pendingResult?.error("PICK_FILE_CANCELLED", "File picking was cancelled", null)
                Toast.makeText(activity, "文件选择已取消", Toast.LENGTH_SHORT).show()
            }
            pendingResult = null
            currentUriType = null  // 重置类型
            return true
        }
        return false
    }
}